<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, h } from "vue";
import { router } from "@/router";
import {
  get_department_ip,
  add_department_ip,
  delete_department_ip,
  update_department_ip,
} from "@/api/asset";
import { message } from "@/utils/message";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { ActionButtons } from "@/components/DynamicTable/components";

const props = defineProps<{
  task: string;
}>();

defineOptions({
  name: "Weight",
});

// 表单引用
const searchFormRef = ref<DynamicFormInstance>();
const addFormRef = ref<DynamicFormInstance>();
const updateFormRef = ref<DynamicFormInstance>();
const tableRef = ref<DynamicTableInstance>();

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const showAddDialog = ref(false);
const showUpdateDialog = ref(false);
const updateId = ref(0);

// 开关状态数据
const switchStates = ref({
  adjacentAlgorithm: true, // 相邻算法开关，默认开启
  fingerprintInference: true, // 指纹推理开关，默认开启
});

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 搜索表单数据
const searchFormData = reactive({
  department: "",
  ipscope: "",
});

// 新增表单数据
const addFormData = reactive({
  department: "",
  ipscope: "",
});

// 更新表单数据
const updateFormData = reactive({
  department: "",
  ipscope: "",
});

// 搜索表单配置
const searchFormConfig: FormItemConfig[] = [
  {
    type: "input",
    key: "department",
    name: "策略",
    placeholder: "策略",
    params: {
      clearable: true,
    },
  },
  {
    type: "input",
    key: "ipscope",
    name: "方法",
    placeholder: "方法",
    params: {
      clearable: true,
    },
  },
];

// 新增表单配置
const addFormConfig: FormItemConfig[] = [
  {
    type: "input",
    key: "department",
    name: "策略",
    placeholder: "策略",
    required: true,
    rules: [{ required: true, message: "请输入策略", trigger: "blur" }],
  },
  {
    type: "input",
    key: "ipscope",
    name: "方法",
    placeholder: "方法",
    required: true,
    rules: [{ required: true, message: "请输入方法", trigger: "blur" }],
  },
];

// 更新表单配置
const updateFormConfig: FormItemConfig[] = [
  {
    type: "input",
    key: "department",
    name: "策略",
    placeholder: "策略",
    required: true,
    rules: [{ required: true, message: "请输入策略", trigger: "blur" }],
  },
  {
    type: "input",
    key: "ipscope",
    name: "方法",
    placeholder: "方法",
    required: true,
    rules: [{ required: true, message: "请输入方法", trigger: "blur" }],
  },
];

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "策略",
    prop: "department",
    show: true,
    key: "department",
  },
  {
    label: "方法",
    prop: "ip_range",
    show: true,
    key: "ip_range",
    slot: "method",
  },
  {
    label: "操作",
    prop: "action",
    width: 200,
    show: true,
    key: "action",
    render: (row: any) => {
      const actions = [
        {
          type: "button",
          label: "应用",
          command: "edit",
          buttonType: "success",
          link: true,
        },
        {
          type: "button",
          label: "关闭",
          command: "delete",
          buttonType: "warning",
          link: true,
        },
      ];

      return h(ActionButtons, {
        actions: actions as any[],
        row,
        onAction: (command: string, row: any) => {
          handleTableAction(command, row);
        },
      });
    },
  },
];

// 原始数据
const originalData = [
  {
    id: 1,
    department: "疑似自有资产发现",
    ip_range: "111.23.14.1/24",
  },
];

// 获取部门IP列表
const getDepartmentIpList = async () => {
  loading.value = true;

  // 模拟API调用延迟
  setTimeout(() => {
    let filteredData = [...originalData];

    // 根据搜索条件过滤数据
    if (searchFormData.department) {
      filteredData = filteredData.filter((item) =>
        item.department.includes(searchFormData.department)
      );
    }

    if (searchFormData.ipscope) {
      filteredData = filteredData.filter((item) =>
        item.ip_range.includes(searchFormData.ipscope)
      );
    }

    // 模拟分页
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    tableData.value = filteredData.slice(start, end);
    pagination.total = filteredData.length;

    loading.value = false;
  }, 300);
};

// 搜索
const handleSearch = (value: any) => {
  pagination.currentPage = 1;
  getDepartmentIpList();
};

// 重置搜索
const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  getDepartmentIpList();
};

// 新增
const handleAdd = async (value: any) => {
  try {
    const res = await add_department_ip({
      ip_range: value.ipscope,
      department: value.department,
    });

    if (res.code === 2000) {
      ElMessage.success("添加成功");
      showAddDialog.value = false;
      getDepartmentIpList();
    }
  } catch (error) {
    console.error("添加失败:", error);
    ElMessage.error("添加失败");
  }
};

// 编辑
const handleEdit = (row: any) => {
  updateId.value = row.id;
  updateFormData.department = row.department;
  updateFormData.ipscope = row.ip_range;
  showUpdateDialog.value = true;
};

// 更新
const handleUpdate = async (value: any) => {
  try {
    const res = await update_department_ip({
      id: updateId.value,
      ip_range: value.ipscope,
      department: value.department,
    });

    if (res.code === 2000) {
      ElMessage.success("更新成功");
      showUpdateDialog.value = false;
      getDepartmentIpList();
    }
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新失败");
  }
};

// 删除
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这条记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const res = await delete_department_ip({ id });
    if (res.code === 2000) {
      ElMessage.success("删除成功");
      getDepartmentIpList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 分页处理
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  getDepartmentIpList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getDepartmentIpList();
};

// 取消新增
const handleCancelAdd = () => {
  showAddDialog.value = false;
  addFormRef.value?.resetFields();
};

// 取消更新
const handleCancelUpdate = () => {
  showUpdateDialog.value = false;
  updateFormRef.value?.resetFields();
};

// 打开新增对话框
const handleOpenAddDialog = () => {
  addFormData.department = "";
  addFormData.ipscope = "";
  showAddDialog.value = true;
};

// 处理表格操作
const handleTableAction = (command: string, row: any) => {
  switch (command) {
    case "edit":
      handleApply(row);
      break;
    case "delete":
      handleClose(row);
      break;
    default:
      console.log("未知操作:", command);
  }
};

// 应用策略
const handleApply = async (row: any) => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500));

    ElMessage.success(`策略"${row.department}"应用成功！`);

    // 可以在这里添加实际的应用逻辑
    console.log("应用策略:", row);
  } catch (error) {
    console.error("应用失败:", error);
    ElMessage.error("应用失败");
  }
};

// 关闭策略
const handleClose = async (row: any) => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500));

    ElMessage.success(`策略"${row.department}"关闭成功！`);

    // 可以在这里添加实际的关闭逻辑
    console.log("关闭策略:", row);
  } catch (error) {
    console.error("关闭失败:", error);
    ElMessage.error("关闭失败");
  }
};

// 处理开关状态变化
const handleSwitchChange = (
  switchType: string,
  value: string | number | boolean
) => {
  const switchNames: Record<string, string> = {
    adjacentAlgorithm: "相邻算法",
    fingerprintInference: "指纹推理",
  };

  const boolValue = Boolean(value);
  const action = boolValue ? "开启" : "关闭";
  ElMessage.success(`${switchNames[switchType]}已${action}`);

  console.log(`${switchNames[switchType]}状态变化:`, boolValue);
};

// 生命周期
onMounted(() => {
  getDepartmentIpList();
});

onUnmounted(() => {
  // 清理定时器或其他资源
  loading.value = false;
});
</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchFormData"
          :form-config="searchFormConfig"
          :gutter="16"
          label-width="80px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="mt-4">
      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        :showToolbar="true"
        border
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <!-- 方法列插槽 -->
        <template #method>
          <div class="method-switches">
            <div class="switch-item">
              <span class="switch-label">相邻算法</span>
              <el-switch
                v-model="switchStates.adjacentAlgorithm"
                size="small"
                @change="handleSwitchChange('adjacentAlgorithm', $event)"
              />
            </div>
            <div class="switch-item">
              <span class="switch-label">指纹推理</span>
              <el-switch
                v-model="switchStates.fingerprintInference"
                size="small"
                @change="handleSwitchChange('fingerprintInference', $event)"
              />
            </div>
          </div>
        </template>

        <!-- <template #toolbar-left>
          <el-button type="primary" @click="handleOpenAddDialog">
            新建产
          </el-button>
        </template> -->
      </DynamicTable>
    </el-card>

    <!-- 新增对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="新建产"
      width="500px"
      destroy-on-close
      @close="handleCancelAdd"
    >
      <DynamicForm
        ref="addFormRef"
        v-model="addFormData"
        :form-config="addFormConfig"
        label-width="100px"
        type="submit"
        @submit="handleAdd"
        @cancel="handleCancelAdd"
      />
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showUpdateDialog"
      title="编辑产"
      width="500px"
      destroy-on-close
      @close="handleCancelUpdate"
    >
      <DynamicForm
        ref="updateFormRef"
        v-model="updateFormData"
        :form-config="updateFormConfig"
        label-width="100px"
        type="submit"
        @submit="handleUpdate"
        @cancel="handleCancelUpdate"
      />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
}

:deep(.el-pagination) {
  justify-content: right;
  margin-top: 10px;
  margin-right: 30px;
}
.gather-container {
  display: block;
  margin-bottom: 10px;
}

.min-w-input {
  width: 300px;
}

.el-btn-zese {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

.el-btn-zese.is-disabled,
.el-btn-zese.is-disabled:focus,
.el-btn-zese.is-disabled:hover {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

// 方法开关样式
.method-switches {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px 0;
}

.switch-item {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 120px;
}

.switch-label {
  font-size: 12px;
  color: #606266;
}
</style>
